package com.flyshop.web.admin;

import com.flyshop.core.base.BaseController;
import com.flyshop.core.entity.DataVo;
import com.flyshop.core.entity.PageVo;
import com.flyshop.module.security.model.Permission;
import com.flyshop.module.security.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@Controller
@RequestMapping("/admin/permission")
public class PermissionAdminController extends BaseController {
    @Autowired
    protected PermissionService srv;

    //同步所有权限
    @GetMapping("/sync")
    @ResponseBody
    public DataVo getSyncAllPermission(){
        if(srv.getSyncAllPermission()){
            return DataVo.success("同步权限成功");
        }
        return DataVo.failure("同步权限失败");
    }

    //删除权限节点
    @PostMapping("/del")
    @ResponseBody
    public DataVo deletePermission(@RequestParam(value = "id") int id){
        DataVo data = DataVo.failure("操作失败");
        if(srv.deletePermission(id)){
            data = DataVo.success("该权限已删除");
        }else{
            data = DataVo.failure("删除失败或者不存在！");
        }
        return data;
    }

    @GetMapping(value = "/update/{id}")
    public String updatePermissions(@PathVariable int id, ModelMap modelMap){
        Permission permission = srv.findPermissionById(id);
        modelMap.put("permission", permission);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("permission/update");
    }

    //处理用户组信息
    @PostMapping("/update_save")
    @ResponseBody
    public DataVo updatePermissionsSave(@Valid Permission permission, BindingResult result){
        DataVo data = DataVo.failure("操作失败");
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return DataVo.failure(error.getDefaultMessage());
                }
                return null;
            }
            data = srv.updatePermissions(permission);
        } catch (Exception e) {
            data = DataVo.failure(e.getMessage());
        }
        return data;
    }

    @GetMapping(value = "/list")
    public String roleList(@RequestParam(value = "p", defaultValue = "1") int pageNum, ModelMap modelMap){
        PageVo<Permission> pageVo=srv.getPermissionListPage(pageNum,20);
        modelMap.put("pageVo", pageVo);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("permission/list");
    }



}
